package com.watch.system.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.watch.system.common.result.PageResult;
import com.watch.system.common.result.Result;
import com.watch.system.common.util.ExcelUtils;
import com.watch.system.model.entity.CarAuth;
import com.watch.system.model.form.AuthForm;
import com.watch.system.model.form.SysDescForm;
import com.watch.system.model.query.CarAuthPageQuery;
import com.watch.system.model.query.CarUserPageQuery;
import com.watch.system.model.vo.*;
import com.watch.system.plugin.easyexcel.AuthImportListener;
import com.watch.system.plugin.easyexcel.UserAppImportListener;
import com.watch.system.service.AuthService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * 认证
 * @author gmli
 * @since 2024/10/16
 */
@Tag(name = "认证认证接口")
@RestController
@RequestMapping("/api/car/auth")
@RequiredArgsConstructor
public class AuthenticationController {

    private final AuthService authService;

    @Operation(summary = "认证分页列表")
    @GetMapping("/page")
    public PageResult<CarAuthPageVO> getAuthPage(
            @ParameterObject CarAuthPageQuery queryParams
    ) {
        IPage<CarAuthPageVO> result = authService.getAuthPage(queryParams);
        return PageResult.success(result);
    }

    @Operation(summary = "修改认证")
    @PutMapping(value = "/authCar")
     public Result updateAuth(@RequestBody @Validated AuthForm authForm) {
        boolean result = authService.updateAuth(authForm.getAuthenticationId(), authForm);
        return Result.judge(result);
    }

    @Operation(summary = "修改认证状态")
    @PatchMapping(value = "/{AuthId}/status")
    public Result updateAuthStatus(
            @Parameter(description = "认证ID") @PathVariable Long authenticationId,
            @Parameter(description = "认证状态(1:启用;0:禁用)") @RequestParam Integer status
    ) {
        boolean result = authService.update(new LambdaUpdateWrapper<CarAuth>()
                .eq(CarAuth::getAuthenticationId, authenticationId)
                .set(CarAuth::getStatus, status)
        );
        return Result.judge(result);
    }


    @Operation(summary = "删除认证")
    @DeleteMapping("/{ids}")
    public Result deleteAuth(@Parameter(description = "认证ID，多个以英文逗号(,)分割") @PathVariable String ids) {
        boolean result = authService.deleteAuth(ids);
        return Result.judge(result);
    }

    @Operation(summary = "认证导入模板下载")
    @GetMapping("/templateAuth")
    public void downloadTemplate(HttpServletResponse response) throws IOException {
        String fileName = "认证模板.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));

        String fileClassPath = "excel-templates" + File.separator + fileName;
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(fileClassPath);

        ServletOutputStream outputStream = response.getOutputStream();
        ExcelWriter excelWriter = EasyExcel.write(outputStream).withTemplate(inputStream).build();

        excelWriter.finish();
    }

    @Operation(summary = "导入认证")
    @PostMapping("/impAuth")
    public Result importAuth(MultipartFile file) throws IOException {
        AuthImportListener listener = new AuthImportListener();
        String msg = ExcelUtils.importExcel(file.getInputStream(), CarAuthImportVO.class, listener);
        return Result.success(msg);
    }

    @Operation(summary = "导出认证")
    @GetMapping("/expAuth")
    public void exportAuth(CarAuthPageQuery queryParams, HttpServletResponse response) throws IOException {
        String fileName = "认证数据.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));

        List<CarAuthExportVO> exportUserList = authService.listExportAuths(queryParams);
        EasyExcel.write(response.getOutputStream(), CarUserExportVO.class).sheet("认证列表")
                .doWrite(exportUserList);
    }
}
